import { Toast } from 'antd-mobile';
import axios from 'axios';
import { getStore } from './common';
import handleHttpError from './handleHttpError';
import { BaseURI } from './config';

interface Headers {
    'Accept': string;
    'Content-Type': string;
    'Authorization'?: string|null;

}
interface RequestConfig {
    headers: Headers;
    params?: object;
}

const getRequestConfig = () => {
    let requestConfig: RequestConfig;    
    requestConfig = {
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Authorization': !!getStore('access_token') ? getStore('access_token') : '',
        }   
    };
    return requestConfig;
};

const http = {
    async get( url: string = '', data = {} ) {
        url = BaseURI + url;
        try {
            let requestConfig = getRequestConfig();
            if (!!data) {
                requestConfig.params = data;
            }
            let result = await axios.get(url, requestConfig);
            return result.data;
        } catch ( error ) {
            handleHttpError(error, Toast);
        }
    },
    async post(url: string = '', data = {}) {
        try {
            let requestConfig = getRequestConfig();            
            let result = await axios.post(url, data, requestConfig );
            return result.data;
        } catch (error) {
            handleHttpError(error, Toast);
        }

    },
    async fetchJson( url: string ) {
        try {
            let result = await axios.get(url);
            return result.data;
        } catch ( error ) {
            handleHttpError( error, Toast );
        }
    }
};

export default http;